package com.gy.studyonlineapp.fragment;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gy.studyonlineapp.R;
import com.gy.studyonlineapp.ViewModel.ViewModelVideo;
import com.gy.studyonlineapp.activity.KnowledgeActivity;
import com.gy.studyonlineapp.activity.MyCollectActivity;
import com.gy.studyonlineapp.adapter.CollectItemAdapter;
import com.gy.studyonlineapp.adapter.VideoAdapter;
import com.gy.studyonlineapp.common.Constants;
import com.gy.studyonlineapp.entity.CollectionItem;
import com.gy.studyonlineapp.entity.KnowledgeItem;
import com.gy.studyonlineapp.entity.Question;
import com.gy.studyonlineapp.entity.Video;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FragmentVideo extends Fragment {

    private ViewModelVideo mViewModel;

    private ListView listView;
    private SensorManager sensorManager;
    private Jzvd.JZAutoFullscreenListener sensorEventListener;
    private View view;
    private ImageView java_view;
    private ImageView android_view;
    private Boolean flag = true;

    public static FragmentVideo newInstance() {
        return new FragmentVideo();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_video, container, false);
        listView = view.findViewById(R.id.player_list_view);
        java_view = view.findViewById(R.id.imageView6);
        android_view = view.findViewById(R.id.imageView7);
        // 为搜索功能绑定事件
        ImageView searchBtn = view.findViewById(R.id.select_p01);
        EditText editText = view.findViewById(R.id.select01);
        ImageButton clean = view.findViewById(R.id.select_p02);

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取文本框中的内容
                String title = editText.getText().toString();
                if (!title.isEmpty()) {
                    // 进行查询数据库
                    String url = "http://" + Constants.localhost + ":8080/search-by-title";
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("title", title)
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {}
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Gson gson = new Gson();
                            KnowledgeItem knowledgeItem = gson.fromJson(response.body().string(), KnowledgeItem.class);
                            String objectId = knowledgeItem.getId();
                            if (!objectId.isEmpty()) {
                                Intent intent = new Intent(getActivity(), KnowledgeActivity.class);
                                intent.putExtra("objectId",objectId);
                                startActivity(intent);
                            } else {
                                Toast.makeText(getActivity(), "查不到结果,请重新输入标题", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(getContext(), "请输入文章标题", Toast.LENGTH_SHORT).show();
                }
            }
        });
        clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 将EditText内容清空
                editText.setText("");
            }
        });


        initData();
        java_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = !flag;
                initData();
            }
        });
        android_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = !flag;
                initData();
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {}

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (Jzvd.CURRENT_JZVD == null) return;
                int lastVisibleItem = firstVisibleItem + visibleItemCount;
                int currentPlayPosition = Jzvd.CURRENT_JZVD.positionInList;
                Log.e("Test", "onScrollReleaseAllVideos: " +
                        currentPlayPosition + " " + firstVisibleItem + " " + currentPlayPosition + " " + lastVisibleItem);
                if (currentPlayPosition >= 0) {
                    if ((currentPlayPosition < firstVisibleItem || currentPlayPosition > (lastVisibleItem - 1))) {
                        if (Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                }
            }
        });

        sensorManager = (SensorManager) getActivity().getSystemService(getContext().SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();
        return view;
    }

    private void initData() {
        // 查询数据库获取视频资源
        String type = flag == true ? String.valueOf(1) : String.valueOf(2);
        String url = "http://" + Constants.localhost + ":8080/search-video";
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("type", type)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            List<Video> lists = new ArrayList<>();
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage() + "=============");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                List<Video> list = gson.fromJson(response.body().string(), new TypeToken<List<Video>>() {}.getType());
                for (int i = 0; i < list.size(); i++) {
                    Video item = new Video();
                    item.setPostImg(list.get(i).getPostImg());
                    item.setUrl(list.get(i).getUrl());
                    item.setTitle(list.get(i).getTitle());
                    item.setObjectId(list.get(i).getObjectId());
                    lists.add(item);
                }
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        listView.setAdapter(new VideoAdapter(getContext(), R.layout.fragment_video_item, lists));
                    }
                });
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }


    @Override
    public void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        Jzvd.releaseAllVideos();
    }
}